<script lang="ts" setup>
import {ref,reactive,toRaw} from 'vue';
import {getFriendLinks,deleteLink,queryGroup,addLInk} from '@/api/group-link'
import {message} from "ant-design-vue/lib";
import moment from "moment/moment";
import type { UnwrapRef } from 'vue';
import type { SelectProps } from 'ant-design-vue';
import { DeleteOutlined,EditOutlined} from '@ant-design/icons-vue'

interface linkItem {
  linkId: number,
  linkName: string,
  linkUrl: string,
  linkDesc: string,
  linkLogo: string,
  isActived: number,
  createTime: string,
  updateTime:string,
  groupName?: string
}

interface result  {
  code: number,
  data?: Array<{
    links: Array<linkItem>,
    groupName: string,
    cateGroup:number
  }>,
  msg: string
}


let dataSource = ref<Array<linkItem>>([])
let loading = ref<boolean>(false)

let columns = ref([
  {
    title: 'id',
    dataIndex: 'linkId',
    key: 'linkId',
  },
  {
    title: '友链名称',
    dataIndex: 'linkName',
    key: 'linkName',
  },
  {
    title: 'Logo',
    dataIndex: 'linkLogo',
    key: 'linkLogo',
  },
  {
    title: '友链链接',
    dataIndex: 'linkUrl',
    key: 'linkUrl',
  }, {
    title: "分组",
    dataIndex: 'groupName',
    key: 'groupName',
  }, {
    title: '友链简介',
    dataIndex: 'linkDesc',
    key: 'linkDesc',
  }, {
    title: "创建时间",
    dataIndex: 'createTime',
    key: 'createTime',
  },{
    title:"最后更新时间",
    dataIndex: 'updateTime',
    key: 'updateTime',
  },{
    title:"操作",
    dataIndex: "action",
    key:"action"
  }
])



loading.value = true
getFriendLinks().then((data:any) => {
  loading.value = false
  data.data.forEach((item:any) => {
    item.links.forEach((link:linkItem)  => {
      link["groupName"] = item.groupName
      link["createTime"] = moment(link.createTime).format('YYYY-MM-DD HH:mm:ss')
      link["updateTime"] = moment(link.updateTime).format('YYYY-MM-DD HH:mm:ss')
      dataSource.value.push(link)
    })
  })
}).catch((err) => {
  console.log(err)
  loading.value = false
  message.error("获取友链失败")
})



// 删除

let deleteHandler = (record:linkItem) => {
  console.log('当前行数据',record)
  let key = 'delete'
  message.loading({content:"删除中...",key})
  deleteLink(record.linkId).then((data:any) => {
    if (data.code === 200) {
      message.success({content:"删除成功",key})
      dataSource.value = dataSource.value.filter((item:linkItem) => item.linkId !== record.linkId)
    } else {
      message.error({content:"删除失败",key})
    }
  }).catch((err) => {
    console.log(err)
    message.error({content:"删除失败",key})
  })
}


interface FormState {
  linkName: string;
  isActived: number;
  cateGroup: number;
  linkUrl: string;
  linkDesc: string;
  linkLogo:string,
  className?:string
}

const initFormState:FormState = {
  linkName:"",
  isActived:1,
  cateGroup:1,
  linkUrl:"",
  linkDesc:"欢迎大家来访问哦~",
  linkLogo:"",
  className:""
}

const formState: UnwrapRef<FormState> = reactive({...initFormState});

// 重置表单函数
let resetFormState = () => {
  Object.assign(formState,initFormState)
}


const labelCol = { style: { width: '80px' } };
const wrapperCol = { span: 24 };
const addLoading = ref<boolean>(false);
const open = ref<boolean>(false);

const showModal = () => {
  open.value = true;
  initFormCateGroup()
};


const options1 = ref<SelectProps['options']>([]);

// 获取分组 -- 并初始化表单的分组值
let initFormCateGroup = () => {
  queryGroup().then((res:any) => {
    if (res.code == 200) {
      options1.value = res.data.map((item:{groupName:string,groupId:number}) => {
        return {
          label: item.groupName,
          value: item.groupId,
        }
      })
      formState.cateGroup = options1.value[0].value
    }else {
      formState.cateGroup = 0
    }
  }).catch(err => {
    message.error(err.message)
  })
}

// 选择分组 变化
let cateGroupHandleChange = (e:number) => {
  formState.cateGroup = e
}

// 提交
const handleOk =async  () => {
  try {
    addLoading.value = true;
    let res:any = await addLInk(toRaw(formState))
    if(res.code == 200){
      addLoading.value = false;
      open.value = false;
      resetFormState()
      message.success(res.message)
    }else {
      addLoading.value = false;
      message.error(res.message)
    }
  }catch (e:any) {
    message.error(e.message)
  }
};

// 取消添加 清空所有项目
const handleCancel = () => {
  open.value = false;
  resetFormState() // 初始化表单
  message.warning("已取消")
};
// 添加友链
let addLink = () => {
  showModal()
}


// 更新
let editHandler = (record:linkItem) => {
  console.log('edit',record)
  message.warning('暂未开放')
}

</script>

<template>
  <div class="friend-link">
    <div class="link-utils-box">
      <a-button class="editable-add-btn" @click="addLink">添加友链</a-button>
    </div>
    <a-table :loading="loading" :columns="columns" :dataSource="dataSource">
      <template #bodyCell="{ column,record }">
        <template v-if="column.key=='linkLogo' " :key="record.linkId">
          <a-avatar :src="record.linkLogo" :key="record.linkId"/>
        </template>

        <template v-else-if="column.key == 'action' ">
          <a-button style="margin-right: 15px" type="primary" primary @click="editHandler(record)">
            <EditOutlined />编辑
          </a-button>
          <a-button type="primary" danger @click="deleteHandler(record)">
                    <DeleteOutlined />删除
          </a-button>
        </template>
      </template>
    </a-table>


    <a-modal v-model:open="open" title="添加友链" @ok="handleOk">
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="addLoading" @click="handleOk">提交</a-button>
      </template>
      <a-form style="margin-top: 35px" label-align="left" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="友链名称">
          <a-input v-model:value="formState.linkName" placeholder="添加友链的名称" />
        </a-form-item>
        <a-form-item label="友链链接">
          <a-input v-model:value="formState.linkUrl" placeholder="友情链接"/>
        </a-form-item>
        <a-form-item label="友链分组">
          <a-space>
            <a-select
                ref="select"
                v-model:value="formState.cateGroup"
                style="width: 120px"
                :options="options1"
                @focus="focus"
                @change="cateGroupHandleChange"
            ></a-select>
          </a-space>
        </a-form-item>
        <a-form-item label="友链logo">
          <a-input v-model:value="formState.linkLogo" placeholder="友情链接logo地址" />
        </a-form-item>
        <a-form-item label="样式类名">
          <a-input v-model:value="formState.className" placeholder="预设类名样式" />
        </a-form-item>
        <a-form-item label="友链状态">
          <a-radio-group v-model:value="formState.isActived">
            <a-radio :value=1>开启</a-radio>
            <a-radio :value=0>关闭</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="友链介绍">
          <a-textarea v-model:value="formState.linkDesc" placeholder="快添加您的介绍吧~" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.link-utils-box {
  padding: 10px;
  box-sizing: border-box;
}
</style>
